package com.thougtful.factory;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取单例对象的工厂
 *
 * @author yushun
 * @createTime 2022/10/18 - 15:52
 **/
public final class SingletonFactory {

    public static final Map<String, Object> SINGLETON_OBJECT_MAP = new ConcurrentHashMap<>();

    private SingletonFactory() {}

    public static <T> T getSingleton(Class<T> c) {
        if (null == c) {
            throw new IllegalArgumentException("object class can't be null");
        }
        String key = c.toString();
        if (SINGLETON_OBJECT_MAP.containsKey(key)) {
            return c.cast(SINGLETON_OBJECT_MAP.get(key));
        }
        return c.cast(SINGLETON_OBJECT_MAP.computeIfAbsent(key, k -> {
            try {
                return c.getDeclaredConstructor().newInstance();
            } catch (InstantiationException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }));
    }

}
